package com.zjlanyun.erp.interior.production;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.Button;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.yolanda.nohttp.rest.Response;
import com.zjlanyun.erp.Data;
import com.zjlanyun.erp.MainApplication;
import com.zjlanyun.erp.R;
import com.zjlanyun.erp.network.WebApi;
import com.zjlanyun.erp.nohttp.HttpRequest;
import com.zjlanyun.erp.nohttp.SimpleHttpListener;
import com.zjlanyun.erp.rfid.m10.u8.activity.OutPowerActivity;
import com.zjlanyun.erp.rfid.m10.u8.reader.ERROR;
import com.zjlanyun.erp.utils.Toastor;
import com.zjlanyun.erp.view.BaseRFIDActivity;

import org.json.JSONObject;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.OnClick;

public class ActivateCard extends BaseRFIDActivity {

    @Bind(R.id.tv_result) TextView tv_result;
    @Bind(R.id.tv_epc) TextView tv_epc;
    @Bind(R.id.tv_status) TextView tv_status;
    @Bind(R.id.tv_newepc) TextView tv_newepc;
    @Bind(R.id.btn_submit) Button btn_submit;

    private boolean scaning = false;
    private String apiUrl = "";
    private String newEPC = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activate_card);
        initBaseView();
        initView();
    }

    private void initView() {
        Bundle bundle = getIntent().getExtras();
        title.setText(bundle.getString("title"));
        btn_submit.setText(bundle.getString("title"));
        apiUrl = WebApi.production();
        successMsg =  bundle.getString("title") + "成功";
        failMsg = bundle.getString("title") + "失败";
    }

    /**
     * 开始扫描
     */
    public void startScan() {
        tv_epc.setText("");
        tv_newepc.setText("");
        newEPC = "";
        tv_status.setText("盘询开始");
        scanNumber = 1;
        scaning = true;
        super.startScan();
    }

    /**
     * 停止扫描
     */
    public void stopScan() {
        tv_status.setText("盘询结束");
        scaning = false;
        super.stopScan();
    }

    public void refreshText() {
        super.refreshText();
        tv_result.setText(String.format("扫描到:%d个", m_curInventoryBuffer.lsTagList.size()));
        if (m_curInventoryBuffer.lsTagList.size() > 0) {
            tv_epc.setText(m_curInventoryBuffer.lsTagList.get(0).getStrEPC().replace(" ", ""));
        }
    }

    @OnClick(R.id.btn_submit)
    public void readCard(){
        if (tv_epc.getText().toString().equals("")){
            Toastor.getInstance().showShortToast("请先扫卡");
            return;
        }

        HashMap<String, Object> param = new HashMap<>();
        param.put("epc", tv_epc.getText().toString());
        param.put("FActionFlag", "read");
        Bundle bundle = getIntent().getExtras();
        if (bundle.getString("title").equals("开卡")) {
            param.put("Flag", "kaika");
        } else if (bundle.getString("title").equals("清卡")) {
            param.put("Flag", "qingka");
        }
        HttpRequest client = new HttpRequest(mContext,apiUrl,"activateCard", JSON.toJSONString(param), true, true);
        client.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onSucceed(int what, Response<JSONObject> response) {
                JSONObject data = response.get().optJSONObject("data");
                setEPC(tv_epc.getText().toString());
                newEPC = data.optString("newEPC");
                readOrWrite(ActionType.write, AccessAreaType.epc, "1", data.optString("FValue"), 2, data.optString("prefix")+data.optString("newEPC"));
//                tv_epc.setText("");
            }
        });
    }

    /**
     * 开卡操作中写卡成功之后提交到数据库
     */
    private void postWriteCard(){
        HashMap<String, Object> param = new HashMap<>();
        param.put("epc", newEPC);
        param.put("FActionFlag", "write");
        HttpRequest client = new HttpRequest(mContext, apiUrl, "activateCard", JSON.toJSONString(param), true, true);
        client.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onSucceed(int what, Response<JSONObject> response) {
                Toastor.getInstance().showShortToast(successMsg);
            }
        });
    }


    public void writeResult(byte type, String msg){
        Bundle bundle = getIntent().getExtras();
        if (bundle.getString("title").equals("开卡")) {
            if (type == ERROR.SUCCESS) {
                tv_newepc.setText(newEPC);
                postWriteCard();
            } else if (type == ERROR.FAIL) {
                super.writeResult(type, msg);
            }
        } else if (bundle.getString("title").equals("清卡")) {
            if (type == ERROR.SUCCESS) {
                tv_newepc.setText(newEPC);
            }
            super.writeResult(type, msg);
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == 80 && Build.MODEL.equals(Data.RFID_DEVICE)) {
            if (scaning) {
                stopScan();
            } else {
                startScan();
            }
            return false;
        } else if ((keyCode == 131 && Build.MODEL.equals(Data.RFID_DEVICE)) || (keyCode == 132 && Build.MODEL.equals(Data.RFID_DEVICE)) || (keyCode == 133 && Build.MODEL.equals(Data.RFID_DEVICE))) {
            Intent intent = new Intent(mContext, OutPowerActivity.class);
            intent.putExtra("from", "RFID" + className);
            startActivity(intent);
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }
}
